<?php
namespace TwinPeaks\Core\Html;
use TwinPeaks\Core as Core;

require_once __DIR__ . '/../CSGMLElement.php';

class CElement extends Core\CSGMLElement
{
	const ATTR_CLASS = 'class';
	
	/**
	 * 
	 * @return CElement
	 */
	function addClass($classToAdd)
	{
		if (is_array($classToAdd))
			$classToAdd = join(' ', $classToAdd);
		if (!$this->hasAttr(self::ATTR_CLASS))
			$this->setAttr(self::ATTR_CLASS, $classToAdd);
		else
		{
			$parts = explode(' ', $this->getAttr(self::ATTR_CLASS));
			foreach ($parts as $class)
				if (!strcasecmp($class, $classToAdd))
					return $this;
			$parts[] = $classToAdd;
			$this->setAttr(self::ATTR_CLASS, join(' ', $parts));
		}
		
		return $this;
	}
	
	/**
	 * @return CElement
	 */
	function removeClass($classToRemove)
	{
		if (!$this->hasAttr(self::ATTR_CLASS))
			return $this;
		$parts = explode(' ', $this->getAttr(self::ATTR_CLASS));
		$newAttrValue = [];
		foreach ($parts as $class)
			if (strcasecmp($class, $classToRemove))
				$newAttrValue[] = $class;
		if (!count($newAttrValue))
			$this->removeAttr(self::ATTR_CLASS);
		else
			$this->setAttr(self::ATTR_CLASS, join(' ', $newAttrValue));
		
		return $this;
	}
	
	/**
	 * @return boolean
	 */
	final function hasClass($needle)
	{
		if (!$this->hasAttr(self::ATTR_CLASS))
			return false;
		$parts = explode(' ', $this->getAttr(self::ATTR_CLASS));
		foreach ($parts as $class)
			if (!strcasecmp($class, $needle))
				return true;
		
		return false;
	}
	
	/**
	 * @return CElement
	 */
	function toggleClass($class)
	{
		if ($this->hasClass($class))
			$this->removeClass($class);
		else
			$this->addClass($class);
		
		return $this; 
	}
}
